/*
 * 工作流设计
 * @Author: gk 
 * @Date: 2018-04-25 14:46:08 
 * @Last Modified by: gk
 * @Last Modified time: 2018-05-17 10:23:36
 */
layui.config({
}).use(['element', 'zlConfig', 'zlContext', 'zltreemenu', 'zlSelectMultiple', 'zlSelectEx', 'zlpoptree', 'zlSelecttree', 'table', 'layer', 'form', 'zlPinYin', 'upload'], function (exports) {
	var $ = layui.$
		, zlContext = layui.zlContext
		, zltreemenu = layui.zltreemenu
		, layer = layui.layer
		, table = layui.table
		, form = layui.form
		, upload = layui.upload
		, zlPinYin = layui.zlPinYin
		, zlConfig = layui.zlConfig
		, statusName = zlConfig.global.result.statusName
		, msgName = zlConfig.global.result.msgName
		, dataName = zlConfig.global.result.dataName
		, OK = zlConfig.global.result.okState
		, fullheight = 'full-30'
		, customCurr = 1;

	var treeObj,
		fromlayerIndex,
		treeAction = {
		raiseResDataEvent: function (node) {
			var currNode = node;
			if (!node) {
				var nodes = treeObj.getSelectedNodes();
				if (nodes.length > 0)
					currNode = nodes[0];
			}
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, currNode);
			}
		}

	treeObj = zltreemenu.render('orgTreeId',{
		dataurl: layui.cache['contentPath'] + '/manager/corefunction/queryorgddata',
		type: 'get',
		tableId: 'tbWorkflow',
		isMove: false
	},{
		onAsyncSuccess: function(event, treeId, treeNode, msg){
			treeObj.selectNode(treeObj.getNodes()[0]);
			treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
		},
		onClick: function (event, treeId, treeNode) {
			customCurr = 1;
			treeAction.raiseResDataEvent(treeNode);
	}
	})
	var workflowTb = table.render({
		elem: '#tbWorkflow'
		, height: fullheight
		, response: zlConfig.global.gridResponse
		, limit: 20
		, limits: [20,50, 100, 200, 500, 1000]
		, page: true
		, updId: "0036B3466EC54125B48C993415FCD017"
		, toolbar: "#toolbarWorkflow"
		, defaultToolbar: []
		, sortload:true
		, cols: [[
			{ type: 'numbers', fixed: 'left', title: '#' }
			, { type: 'checkbox', fixed: 'left' }
			, { field: 'name', title: '流程名称', width: 100, sort:true }
			, { field: 'revision', title: '流程版本', width: 100, sort:true }
			, { field: 'key', title: '流程key', width: 300}
			, {
				field: 'isEnable', title: '生效', width: 80, templet: function (d) {
					return '<input type="checkbox" name="isEnable" value="' + d.isEnable + '" disabled lay-skin="switch" lay-text="是|否" lay-filter="isEnable" ' + (d.isEnable == 1 ? 'checked' : '') + '>';
				}
			}
			, { field: 'lastUpdateTime', title: '修改时间', width: 100, sort:true }
			, { field: 'functionName', title: '关联功能', width: 100, sort:true }
			, { fixed: 'right', width: 320, title: '操作', align: 'center', toolbar: '#barWorkflow' }
		]]
		, event:
			{
				onRowdbClick: function (field, row) {
					gridAction.viewRow(row);
				}
			}
	});
	zlContext.noData($('#tbWorkflow').siblings('div').find('div.layui-table-main'))

	var gridAction = {
		currentEditObj: undefined,
		userGridedit: function (orgNode, row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block layui-fluid" lay-filter="divgridWorkflow"> <form id ="frmGridWorkflow" class="layui-form"  action="">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="id" class="layui-input">'
				, '			<input type="text" name="category" class="layui-input">'
				, '			<input type="text" name="revision" class="layui-input">'
				, '			<input type="text" name="version" class="layui-input">'
				, '			<input type="text" name="metaInfo" class="layui-input">'
				, '			<input type="text" name="deploymentId" class="layui-input">'
				, '			<input type="text" name="editorSourceValueId" class="layui-input">'
				, '			<input type="text" name="tenantId" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label"><span style="color:red">*</span>流程名称</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="name" ' + readonly + ' lay-verify="required|processName" placeholder="请输入流程名称"  class="layui-input" autocomplete="off" maxlength="80">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label"><span style="color:red">*</span>流程Key</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="key" disabled lay-verify="required" class="layui-input" autocomplete="off" maxlength="80">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '     <label class="layui-form-label">关联的功能</label>'
				, '     <div class="layui-input-block">'
				, '         <div name="functionId" zlcomponent class="layui-form-select zlpoptree" ' + readonly + ' settings="{multselect:false,method:\'post\',dataurl:\'' + layui.cache['contentPath'] + '/manager/corefunction/query' + '\',formtitle:\'关联功能\'}">'
				, '         </div>'
				, '     </div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmGridWorkflow"  ' + readonly + '>保存</button>'
				// , '		  <button type="reset" class="layui-btn layui-btn-primary ' + (type == 'edit' ? 'layui-hide"' : '"') + readonly + '>重置</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				limit: 999,
				maxmin: true,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '流程编辑' : '流程新增'),
				id: 'coreWorkflowLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					if (type == 'edit') {
						zlContext.autoFill($('#frmGridWorkflow'), row);
						$('#frmGridWorkflow input[name=EDITTYPE]').val('edit');
					}
					else {
						form.render();
						$('#frmGridWorkflow input[name=EDITTYPE]').val('new');
						$('#frmGridWorkflow input[name=category]').val(orgNode.RWID);
						$('#frmGridWorkflow input[name=name]').change(function () {
							var v = $('#frmGridWorkflow input[name=name]').val();
							var v1 = zlPinYin.C(v);
							$('#frmGridWorkflow input[name=key]').val(v1);
						});
					}
					fromlayerIndex = index;
				},
				cancel: function(index, layero){
                    if (type == 'edit' && readonly != 'disabled') {
                         zlContext.isFormDataChange('frmGridWorkflow',gridAction.currentEditObj.data, gridAction, index)
                         return false;
                    }
                } 
			});
		},
		viewRow: function (row) {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length == 0) {
				zlContext.warnMsg('请选择机构节点');
				return;
			}
			gridAction.userGridedit(nodes[0], row, 'edit', true);
		},
		newRow: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length == 0) {
				zlContext.warnMsg('请选择机构节点');
				return;
			}
			gridAction.userGridedit(nodes[0], null, 'new');
		},
		editRow: function (row) {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length == 0) {
				zlContext.warnMsg('请选择机构节点');
				return;
			}
			gridAction.userGridedit(nodes[0], row, 'edit');
		},
		search: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length > 0) {
				layui.event('WM_USERDEF',
					zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, nodes[0]);
			}
		},
		depoly: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要发布的流程');
				return;
			}
			zlContext.confirm('询问', '是否要发布选择的流程?', function (index) {
				ids = [];
				rows.forEach(function (v) { ids.push(v.data ? v.data['id'] : v['id']); });
				// var param = { ids: ids };
				zlContext.post(layui.cache['contentPath'] + '/core/workflow/model/deploy', { ids: ids }, function (result) {
					if (result[statusName] == OK) {
						table.reload('tbWorkflow');
						zlContext.successMsg('流程发布完毕');
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		export: function (row) {
			if ($("#ifexport").length == 0) {
				$("body").append('<iframe id=ifexport style="display:none"></iframe>');
			}
			$("#ifexport").attr("src", layui.cache['contentPath'] + '/core/workflow/model/export?modelId=' + row['id']);
			iframe = $("#ifexport")[0];
			iframe.onload = iframe.onreadystatechange = function iframeload() {
				if (!iframe.readyState || !iframe.readyState == "complete") {
					zlContext.errorMsg("导出失败，请检查流程设计是否有内容！");
				}
			};
		},
		copy: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要复制的流程');
				return;
			}
			var html = [
				'<div class="layui-form " style="height:100%">'
				, '	<div class="layui-form treecopybox" style="height:calc(100% - 94px);overflow:auto;">'
				, '		<ul id="treeCopyOrg" class="ztree" style="float:left"></ul>'
				, '	</div>'
                , '	<div class="treecopybtn"  style="height:54px;overflow:auto;padding-right: 10px;">'
				, '		  <button id="btnCopyCancel" class="layui-btn layui-btn-primary fr" style="color:#555;background-color:#fff">取消</button>'
				, '		  <button class="layui-btn fr mr10" lay-submit lay-filter="btnCopyOk">确定</button>'		  
				, '	</div>'
				, '</div>'];
			var frmobj = layer.open({
				type: 1,
				limit: 999,
				id: 'copyToOrgLayer',
				area: ['500px', '500px'],
				title: '选择要复制到的机构',
				content: html.join(''),
				success: function (layero, index) {
					zltreemenu.render('treeCopyOrg',{
						dataurl: layui.cache['contentPath'] + '/manager/corefunction/queryorgddata',
						type: 'get',
						search: true ,
						isMove: false,
						checkEnable:true,
						chkboxType:{ "Y": "", "N": "" }
					},{})
					// treeAction.loadTree('treeCopyOrg', undefined, undefined, { enable: true, chkboxType: { "Y": "", "N": "" } });
					form.on('submit(btnCopyOk)', function (frm) {
						var treeCopyObj = $.fn.zTree.getZTreeObj("treeCopyOrg");
						var nodes = treeCopyObj.getCheckedNodes(true);
						var descOrgids = [], srcFwids = [];
						if(nodes.length==0){
							zlContext.warnMsg('请选择要复制到的机构！');
							return;
						}
						nodes.forEach(function (v) { descOrgids.push(v['RWID']); });
						rows.forEach(function (v) { srcFwids.push(v['id']); });
						zlContext.post(
							layui.cache['contentPath'] + '/core/workflow/model/copyto',
							{ srcids: srcFwids, descids: descOrgids },
							function (result) {
								if (result[statusName] == OK) {
									zlContext.successMsg('流程复制完毕');
									layer.close(frmobj);
								}
								else {
									zlContext.errorMsg(result[msgName]);
								}
							});
						return false;
					});
					//点击取消关闭弹出层
					$("#btnCopyCancel").on("click",function(){
						layer.close(index);
					})
				},
				resizing:function(layero){
                },
			});
		},
		design: function (row) {
			var nodes = treeObj.getSelectedNodes();
			var html = '<iframe  src="' + layui.cache['contentPath'] + '/workflowservice/editor?id=' + row['id'] + '&orgid='+nodes[0].RWID+'" frameborder="0" scrolling="no" width="100%" height="99.5%"></iframe>';
			var frmobj = layer.open({
				type: 1,
				limit: 999,
				maxmin: true,
				title: '流程设计',  
				id: 'workflowDesignLayer',
				area: ['100%', '100%'],
				content: html,
				cancel: function (index, layero) {
					layer.close(index)
					table.reload('tbWorkflow');
					return false;
				}
			});
		},
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的流程');
				return;
			}
			zlContext.confirm('询问', '是否要删除选择的流程?', function (index) {
				ids = [];
				rows.forEach(function (v) { ids.push(v.data ? v.data['id'] : v['id']); });
				zlContext.deletePost(layui.cache['contentPath'] + '/core/workflow/model/remove', { ids: ids }, function (result) {
					if (result[statusName] == OK) {
						if (rows[0].del) {
							rows[0].del();
						}else {
							gridAction.refreshGrid('del', null);
						}
						
						zlContext.successMsg('删除成功');
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		sumbit: function (fields) {
			var editType = $('#frmGridWorkflow input[name=EDITTYPE]').val();
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/core/workflow/model/add', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/core/workflow/model/modify', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, fields);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		refreshGrid: function (type, row) {
			if (type == 'edit' && gridAction.currentEditObj) {
				table.reload('tbWorkflow');
			}
			else if (type == 'new') {
				table.reload('tbWorkflow');
			}
			else if (type == 'del') {
				table.deleteCheckRows('tbWorkflow');
			}
			form.render();
		}
	}

	$('.zl-container').on('keyup','#edtSeacherValue', function (event) {
		var keyCode = event.keyCode;
			customCurr = 1;
		$('.zl-container').attr('data-search',$(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            $('#btnSeacher').trigger('click');
            isloadsearch = false;
        }
	});

	//头工具栏事件
	table.on('toolbar(tbWorkflow)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		var rows = checkStatus.data;
		switch(obj.event){
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'addWorkflow':
				gridAction.newRow();
				break;
			case 'deleteWorkflow':
				gridAction.deleteRows(rows);
				break;
			case 'copyWorkflow':
				gridAction.copy(rows);
				break;
		};
	});
	//监听行工具事件
	table.on('tool(tbWorkflow)', function (obj) {
		var row = obj.data;
		var layEvent = obj.event;
		gridAction.currentEditObj = obj;
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.deleteRows([obj]);
		} else if (layEvent === 'edit') { //编辑
			gridAction.editRow(row);
		} else if (layEvent == 'design') {
			gridAction.design(row);
		} else if (layEvent == 'export') {
			gridAction.export(row);
		} else if (layEvent == 'depoly') {
			gridAction.depoly([row]);
		}
	});

	form.verify({
		processName: function (value, item) {
			var str = value.substring(0,1);
			if (!isNaN(str)) {
				return '流程名称只能使用字母或中文开头!';
			}
		}
	});


	//提交
	form.on('submit(frmGridWorkflow)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
            gridAction.newFields = frm.field
            return false;
        }
		return gridAction.sumbit(frm.field);
	});

	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (node) {
		var winIndex = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
		var loadGridData = function (id, url, param) {
			workflowTb.reload({
				url: url
				, method: 'post'
				, page:{
					curr:customCurr
				}
				, where: param
				, done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(winIndex);
					upload.render({
						elem: '.workFlowImport'
						, url: layui.cache['contentPath'] + '/core/workflow/model/import'
						, data: {
							modelId: function () {
								return gridAction.currentEditObj.data['id'];
							}
						}
						, accept: 'file'
						, exts: 'xml'
						, acceptMime: 'file/xml'
						, before: function () {
							winIndex = layer.msg('文件上传中，请稍候...', { icon: 16, time: false, shade: 0.1 });
						}
						, done: function (res, index, upload) {
							layer.close(winIndex);
							zlContext.successMsg('流程上传完毕');
						}
					})
					customCurr = curr;
				}
			}, true);
		}

		var params = { ORGID: node.RWID };
		if ($('#edtSeacherValue').val() !== '')
			params['name'] = $('#edtSeacherValue').val();
		loadGridData('tbWorkflow', layui.cache['contentPath'] + '/core/workflow/model/query', params);
	});
    
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();
});